package oceanwiki.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import oceanwiki.entity.Ebook;
import oceanwiki.mapper.EbookMapper;
import oceanwiki.req.EbookQueryReq;
import oceanwiki.req.EbookSaveReq;
import oceanwiki.resp.CommonResp;
import oceanwiki.resp.EbookQueryResp;
import oceanwiki.resp.PageResp;
import oceanwiki.service.IEbookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import oceanwiki.util.CopyUtil;
import oceanwiki.util.SnowFlake;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

/**
 * <p>
 * 电子书 服务实现类
 * </p>
 *
 * @author XBJ
 * @since 2024-09-07
 */
@Service
public class EbookServiceImpl extends ServiceImpl<EbookMapper, Ebook> implements IEbookService {

    @Override
    public PageResp<EbookQueryResp> listByName(EbookQueryReq req) {
        QueryWrapper<Ebook> queryWrapper = new QueryWrapper<Ebook>();
        queryWrapper.like(StringUtils.isNotBlank(req.getName()), "name", req.getName());
        queryWrapper.eq(ObjectUtils.isNotEmpty(req.getCategoryId2()), "category2_id", req.getCategoryId2());

        //创建分页查询参数
        Page<Ebook> page = new Page<>(req.getPage(), req.getSize());
        page = this.baseMapper.selectPage(page, queryWrapper);
        List<EbookQueryResp> resps = CopyUtil.copyList(page.getRecords(), EbookQueryResp.class);

        //创建返回对象
        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setList(resps);
        pageResp.setTotal(page.getTotal());

        return pageResp;
    }

    @Override
    public void save(EbookSaveReq req) {
        Ebook e = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {//新增
            SnowFlake snowFlake = new SnowFlake();
            long id = snowFlake.nextId();
            e.setId(id);
            this.baseMapper.insert(e);
        } else {//更新
            this.baseMapper.updateById(e);
        }
    }

    @Override
    public void delete(Long id) {
        this.baseMapper.deleteById(id);
    }


}
